package com.study.system.inerceptors;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.study.system.dto.ResultData;
import com.study.system.enums.ResultCode;
import com.study.system.utils.JWTUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;


public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的令牌
        String token = request.getHeader("token");
        try {
            JWTUtil.verifyToken(token);
            return true;
        } catch (Exception e) {
            ResultData<String> resultData = ResultData.fail(ResultCode.TOKEN_FAIL);
            String json = new ObjectMapper().writeValueAsString(resultData);
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            response.getWriter().print(json);
            return false;
        }
    }

}
